package com.xgr.wonderful.db;

import java.util.Map;

import android.content.Context;

import com.xgr.wonderful.entity.SuperConversation;


/**
 * DBOpenHelper--->ConversationDao---->DatabaseUtils 
 * 主要方法：(只用操作这里）
 * getConversationList
 * getConversation
 * addConversation
 * delConversation
 * saveConversationList
 * clearAllConversation
 * @author lsj
 *
 */
public class DatabaseUtil {

	    private static DatabaseUtil singletoneDatabaseUtil = null;

	    private ConversationDao mConversationDao; //操作数据 
	    private Map<Integer, SuperConversation> conversationlist;//数据 

	    public static DatabaseUtil getInstance() {
	        if(singletoneDatabaseUtil == null) {
	        	syncInit() ;
	        }
	        
	        return singletoneDatabaseUtil;
	    }
	    
	    private static synchronized void syncInit (){
	    	if (singletoneDatabaseUtil == null){
	    		singletoneDatabaseUtil = new DatabaseUtil() ;
	    	}
	    }

	    private DatabaseUtil() {
	    }
	    
	
	    /**
	     * 与conversation相关的时候，一定要调用的
	     * @param context
	     */
	    public void initConversationDao(Context context) {
	    	if (mConversationDao == null) {
	    		mConversationDao = new ConversationDao(context);
			}
	    }

	    public void closeDB(Context context)
	    {
	    	saveConversationList();
	    	DBOpenHelper.getInstance(context).closeDB();
	    }
	    
	    public Map<Integer, SuperConversation> getConversationList() {
	    	if (conversationlist == null) {
				conversationlist = mConversationDao.getConversationList();
			}
	    	return conversationlist;
	    }
	    
	    public void addConversation(Integer remoteUserid, SuperConversation superConversation) {
	    	if (conversationlist == null) {
	    		getConversationList();
			}
	    	if (!conversationlist.containsKey(remoteUserid)) {
				conversationlist.put(remoteUserid, superConversation);
			}
	    }
	    
	    public void delConversation(Integer remoteUserid) {
	    	if (conversationlist == null) {
	    		getConversationList();
			}
	    	if (conversationlist.containsKey(remoteUserid)) {
				conversationlist.remove(remoteUserid);
			}
	    }
	    
	    public void saveConversationList() {
	    	if (conversationlist != null && mConversationDao != null) {
				mConversationDao.saveConversationList(conversationlist);
			}
	    }
	    
	    public SuperConversation getConversation(Integer key) {
	    	if (conversationlist == null) {
	    		getConversationList();
			}
			return conversationlist.get(key);
	    }
	    
	    public void clearAllConversation() {
	    	if (conversationlist == null) {
				getConversationList();
			}
	    	conversationlist.clear();
	    }
}
